import { message } from 'antd';

import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';

import { useNavigate, useLocation } from 'react-router-dom';
import { useContextSelector } from 'use-context-selector';

import chatService from '@/api/services/chatService';

import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);

import useWindowWidth from '@/hooks/event/use-window-width';
import { logout } from '@/pages/auth/authUtils';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
import { useParams } from '@/router/hooks';
import { useThemeToken } from '@/theme/hooks';

import ChatBox from './components/ChatBox';
import ChatContextProvider, { ChatContext } from './context';
import './styles/chat.css';
import { Quote } from './tools/constants';

import { BrandingEnum } from '@/common';
import { useDatasetPermit } from '@/store/configStore';

import { useConfigActions, useInitializeData, useAppInfo } from '@/store/configStore';

import { useChatActions } from '@/store/chatStore';

import HomeMenuList from '@/pages/components/menus/HomeMenuList';

import CustomeTitle from '@/pages/components/logo/CustomeTitle';
import { useOrchestrationStore } from '@/store/orchestrationStore';

interface Message {
  text: string;
  isUser: boolean;
  loading?: boolean;
  loadingText?: string;
  chatId?: string;
  dataId?: string;
  ts?: number;
  quote?: Quote[];
}

function Chat() {
  const initializeData = useInitializeData();
  const { fetchInitialInfo } = useConfigActions();

  const { isPc } = useWindowWidth();

  const datasetPermit = useDatasetPermit();

  const [logoutVisible, setLogoutVisible] = useState(false);

  const [messageApi, contextHolder] = message.useMessage();
  const [historyMessages, setHistoryMessages] = useState<Message[]>([]);
  const [initChatId, setInitChatId] = useState('');

  const { isMetaHuman, updateChatInfo, actId } = useContextSelector(ChatContext, (s) => s);

  const location = useLocation();

  const appInfo = useAppInfo();
  useEffect(() => {
    if (!appInfo) {
      return;
    }
    const { state } = location;
    const queryParams = new URLSearchParams(location.search);

    if (!state?.msg && !queryParams.get('chatId')) {
      const userMessage = {
        text: appInfo?.welcome_text ? appInfo?.welcome_text : BrandingEnum.welcome_text,
        isUser: false,
      };
      setHistoryMessages([userMessage]);
    }
  }, []);

  const { type, id, sid, chatId } = useParams();

  const [did, setDid] = useState('');

  const { setLinkParams, setConfig, setChatRecordLoading } = useConfigActions();

  const { setSearchQuestion } = useChatActions();

  const { t } = useTranslation();

  interface DataType {
    gender?: string;
    title: string;
    id: string;
    updateTime: string;
    time: string;
    name: {
      title?: string;
      first?: string;
      last?: string;
    };
    email?: string;
    picture: {
      large?: string;
      medium?: string;
      thumbnail?: string;
    };
    nat?: string;
    loading: boolean;
  }

  const [listLeft, setListLeft] = useState<DataType[]>([]);
  const [isChatInitialized, setIsChatInitialized] = useState(false);

  const handleLogoutCancel = () => {
    setLogoutVisible(false);
  };

  const handleLogoutConfirm = async () => {
    setLogoutVisible(false);
    logout();
  };

  useEffect(() => {
    if (id && sid) {
      updateChatInfo(id, sid, did || '');
    }
  }, [id, sid]);

  useEffect(() => {
    console.log(id, sid);
    setSearchQuestion('');

    if (!id || Object.keys(initializeData).length === 0) {
      fetchInitialInfo();
    }
    return () => {};
  }, []);

  const getHisListSide = () => {
    if (chatId) {
      try {
        setChatRecordLoading(true);
        handleHisItemSide(chatId);
      } catch (error) {
      } finally {
        setChatRecordLoading(false);
      }
    }
  };

  const reHisList = () => {};

  useEffect(() => {
    getHisListSide();
  }, []);

  const navigate = useNavigate();

  const changeChatIdQueryParam = (newChatId) => {
    const searchParams = new URLSearchParams(location.search);
    searchParams.set('chatId', newChatId);
    setLinkParams({ id, share_id: sid, chat_id: newChatId });
    navigate(`${location.pathname}?${searchParams.toString()}`);
  };

  const handleHisItemSide = async (selectChatId: string) => {
    if (id && selectChatId) {
      let datasetPermitList = datasetPermit;

      setChatRecordLoading(true);
      const resp = await chatService
        .ChatRecords({ appId: id, chatId: selectChatId, pageSize: 100 })
        .finally(() => {
          setChatRecordLoading(false);
        });

      const data = resp.list;
      const chatIdHistory = selectChatId;

      setInitChatId(selectChatId);
      const msg: Message[] = data.map((item: any) => {
        const textContent = item.value
          .filter((i) => i?.type == 'text')
          .map((i) => i?.text?.content)
          .join('\n');

        const quoteList =
          datasetPermitList?.length > 0
            ? item?.totalQuoteList?.filter((i) => datasetPermitList.includes(i?.datasetId)) || []
            : item?.totalQuoteList || [];

        const isUser = item.obj === 'Human';

        return {
          text: textContent,
          isUser: isUser,
          chatId: chatIdHistory,
          dataId: item?.dataId,
          quote: quoteList,
          userGoodFeedback: item?.userGoodFeedback || '',
          userBadFeedback: item?.userBadFeedback || '',
        };
      });
      setHistoryMessages(msg);
      if (msg?.length == 0) {
        changeChatIdQueryParam('');
      } else {
        changeChatIdQueryParam(selectChatId);
      }
    }
  };

  useEffect(() => {
    const queryParams = new URLSearchParams(location.search);
    if (queryParams.get('chatId') && !actId) {
      return;
    }

    changeChatIdQueryParam(actId);
  }, [actId]);

  const { isInOrchestrationPage } = useOrchestrationStore();

  return (
    <div className="chat-layout flex h-full w-full">
      {contextHolder}

      <div className="flex flex-col" style={{ width: '100%' }}>
        <CustomeTitle />

        <div
          className="flex h-full"
          style={{
            display: 'flex',
            height: isPc
              ? isInOrchestrationPage
                ? 'calc(100vh - 155px)'
                : 'calc(100vh - 55px)'
              : isInOrchestrationPage
              ? 'calc(100% - 155px)'
              : 'calc(100% - 55px)',
            // height: '90%',
            // height: 'calc(90vh - 50px)',
            gap: isMetaHuman ? '20px' : '0',
            padding: '0 20px 20px 20px',
          }}
        >
          <ChatBox
            initialMessages={historyMessages}
            reHisList={reHisList}
            initChatId={initChatId}
            setListLeft={setListLeft}
            listLeft={listLeft}
            setIsChatInitialized={setIsChatInitialized}
            isChatInitialized={isChatInitialized}
          />
        </div>

        <DeleteConfirmModal
          visible={logoutVisible}
          text="确定要退出登录吗?"
          onCancel={handleLogoutCancel}
          onConfirm={handleLogoutConfirm}
          onConfirmText="退出登录"
        />
      </div>

      {isPc && <HomeMenuList />}
    </div>
  );
}

function Render() {
  return (
    <ChatContextProvider>
      <Chat />
    </ChatContextProvider>
  );
}

export default Render;
